import RandomUtil from '@/RandomUtil'
import { monsterTips, waves } from './config/monsterWave'
import ArrayUtil from '@/ArrayUtil'
import BaseUtil from '@/BaseUtil'
import { OrderId } from '@/globals/order'
import { monsterAttr } from './config/monsterAttr'
import AttributeUtil from '@/AttributeUtil'
import BuffUtil from '@/BuffUtil'
import ForceUtil from '@/ForceUtil'
import PlayerUtil from '@/PlayerUtil'
import SelectUtil from '@/SelectUtil'
import { Frame } from '@/frame'
import ColorStr from '@/ColorStr'
import DamageTotal from 'code/Core/System/DamageTotal'
import MonsterReward from './MonsterReward'
import FramePoint from '@/FramePoint'

declare global {
    var game_wave_interval: number
    var game_max_wave: number
    var game_wave: number
}

const 刷怪点 = [
    { x: -3000, y: 2935 },
    { x: 250, y: 3000 },
    { x: 3000, y: 3000 },
    { x: -3100, y: -2980 },
    { x: 370, y: -2930 },
    { x: 3080, y: -3000 },
]

const viewUnitId = FourCC('ushd')

export default class GameMonsters {
    static buffId = 'buff_guanwu_nandu'
    static readonly EnemyPlayerIndex = 10
    static buffType: AppBuffType = {
        id: 'buff_guanwu_nandu',
        name: '难度选择',
        art: 'ReplaceableTextures\\CommandButtons\\BTNAnimateDead.blp',
        // class: "难度",
        attribute: {},
        ubertip: '不同难度怪物属性不同',
        isDebuff: true,
    }
    static waveFrame: Frame
    constructor() {
        game_wave = 0
        game_wave_interval = 60
        game_max_wave = waves.length
        SetPlayerFlagBJ(PLAYER_STATE_GIVES_BOUNTY, true, Player(10))
        SetPlayerFlagBJ(PLAYER_STATE_GIVES_BOUNTY, true, Player(11))
        for (let key in monsterAttr) {
            AttributeUtil.setUnitTypeAttribute(key, monsterAttr[key])
        }
        se.on('GAME_HARD_SELECTED', GameMonsters.开始刷怪)

        new MonsterReward()
    }

    static 开始刷怪() {
        let dz = DzGetGameUI()
        Frame.createBackDrop(dz)
            .setSize(0.05, 0.015)
            .setPoint(FRAMEPOINT_TOP, dz, FRAMEPOINT_TOP, 0, -0.03)
            .setTexture(
                'ReplaceableTextures\\CommandButtons\\BTNLightningShield.blp'
            )
        let root = Frame.createTEXT(dz)
            .setSize(0.05, 0.015)
            .setPoint(FRAMEPOINT_TOP, dz, FRAMEPOINT_TOP, 0, -0.03)
        root.setFont(0.014, 'fonts\\fonts.ttf')
            .setText('第     波')
            .setTextAlignment(TEXTALIGN_CENTER)
        let text = (GameMonsters.waveFrame = Frame.createTEXT(root.current)
            .setSize(0.03, 0.015)
            .setPoint(
                FramePoint.center,
                root.current,
                FramePoint.center,
                0,
                0
            )).setTextColor(218, 2, 56)
        text.setFont(0.014, 'fonts\\fonts.ttf')
            .setText('0')
            .setTextAlignment(TEXTALIGN_CENTER)

        GameMonsters.buffType.attribute.life_p =
            -0.25 + 0.25 * (game_hard_level - 2)
        GameMonsters.buffType.name = '难度' + game_hard_level
        GameMonsters.buffType.attribute.全伤害倍率 =
            -0.25 + 0.25 * (game_hard_level - 2) + 1
        if (game_hard_level >= 5) {
            GameMonsters.buffType.attribute.护甲穿透百分比 =
                0.1 * (game_hard_level - 4)
            GameMonsters.buffType.attribute.法术穿透百分比 =
                0.1 * (game_hard_level - 4)
        }
        BuffUtil.registerBuffType(GameMonsters.buffType)
        // 开始刷怪倒计时;
        BaseUtil.runLater(game_wave_interval, () => {
            GameMonsters.根据波次刷怪(game_wave)
        })

        BaseUtil.onTimer(2.11, (c) => {
            GameMonsters.isWating && GameMonsters.checkMonsterCount()
            return true
        })
    }
    static checkMonsterCount() {
        let es = SelectUtil.getPlayerUnits(GameMonsters.EnemyPlayerIndex)
        let arr = []
        for (let e of es) {
            if (
                IsUnitAliveBJ(e) &&
                GetUnitTypeId(e) != viewUnitId &&
                GetUnitAbilityLevel(e, 'Aloc') == 0
            )
                arr.push(e)
        }

        if (arr.length == 0) {
            GameMonsters.isWating = false
            if (game_wave < waves.length) {
                let gold =
                    200 -
                    game_hard_level * 20 +
                    game_wave * 10 * (7 - game_hard_level)
                PlayerUtil.message(
                    `第|cffffcc00${game_wave}|r波怪物清空，所有玩家奖励补助金：${ColorStr.gold}${gold}。`
                )
                let c = ForceUtil.getUserCount()
                for (let i = 0; i < c; i++) {
                    PlayerUtil.addGoldState(Player(i), gold)
                }
                // 波次结束奖励
                // 承伤奖励
                let takeMax =
                    DamageTotal.getCurrentWaveTakeDamageMaxPlayerIndex()
                if (takeMax != null) {
                    gold =
                        RandomUtil.nextInt(50, 150) +
                        game_wave * RandomUtil.nextInt(30, 60)
                    PlayerUtil.addGoldState(Player(takeMax.index), gold)
                    PlayerUtil.message(
                        `|cffffcc00${GetPlayerName(
                            Player(takeMax.index)
                        )}|r在本次战斗中承受了|cffff3300${R2I(
                            takeMax.value
                        )}|r的伤害，排名第一,额外奖励${
                            ColorStr.gold
                        }${gold}|r金币。`
                    )
                }
                // 伤害奖励
                let makeMax =
                    DamageTotal.getCurrentWaveMakeDamageMaxPlayerIndex()
                if (makeMax != null) {
                    gold =
                        RandomUtil.nextInt(50, 150) +
                        game_wave * RandomUtil.nextInt(30, 60)
                    PlayerUtil.addGoldState(Player(makeMax.index), gold)
                    PlayerUtil.message(
                        `|cffffcc00${GetPlayerName(
                            Player(makeMax.index)
                        )}|r在本次战斗中造成了|cffff3300${R2I(
                            makeMax.value
                        )}|r的伤害最,排名第一,额外奖励${
                            ColorStr.gold
                        }${gold}|r金币。`
                    )
                }
                // 治疗奖励
                let healMax = DamageTotal.getCurrentWaveHealMaxPlayerIndex()
                if (healMax != null) {
                    gold =
                        RandomUtil.nextInt(50, 150) +
                        game_wave * RandomUtil.nextInt(30, 60)
                    PlayerUtil.addGoldState(Player(healMax.index), gold)
                    PlayerUtil.message(
                        `|cffffcc00${GetPlayerName(
                            Player(healMax.index)
                        )}|r在本次战斗中治疗了|cffff3300${R2I(
                            healMax.value
                        )}|r的生命，排名第一,额外奖励${
                            ColorStr.gold
                        }${gold}|r金币。`
                    )
                    // 下波怪物提示
                }
                PlayerUtil.message(`下波怪将在${game_wave_interval}秒后到达`)
                BaseUtil.runLater(game_wave_interval, () =>
                    GameMonsters.根据波次刷怪(game_wave)
                )
            } else {
                PlayerUtil.message(`已经击杀所有怪物，游戏结束`)
            }
        }
    }

    static isWating = false
    static 根据波次刷怪(w: number) {
        se.emit('怪物刷新')
        let ns = waves[w]
        if (w % 5 != 4) {
            let info = monsterTips[w]
            PlayerUtil.message(
                `第|cffffcc00${game_wave + 1}|r波怪${info.name}物来袭，${
                    info.tip
                }`
            )
            BaseUtil.onTimer(1, (c) => {
                let t = GameMonsters.随机刷怪点()
                for (let item of t) {
                    let { x, y } = item
                    let id = ArrayUtil.randomElement(ns)
                    let u = GameMonsters.create(id, x, y)
                    IssuePointOrderById(u, OrderId.Attack, 0, 0)
                }
                if (c >= 10) GameMonsters.isWating = true
                return c < 10
            })
        } else {
            let id = ArrayUtil.randomElement(ns)
            GameMonsters.创建boss(id)
            PlayerUtil.message(`Bossg来袭击`)
            GameMonsters.isWating = true
        }
        game_wave++
        GameMonsters.waveFrame.setText(game_wave.toString()).setSize(0.06, 0.03)
    }
    static create(id: string, x: number, y: number) {
        let u = CreateUnit(
            Player(GameMonsters.EnemyPlayerIndex),
            id,
            x,
            y,
            RandomUtil.randomAngle()
        )
        BuffUtil.addBuff(u, GameMonsters.buffId)
        return u
    }
    static 随机刷怪点() {
        let t = []
        for (let i = 0; i < 10000; i++) {
            let p = ArrayUtil.randomElement(刷怪点)
            if (!t.includes(p)) {
                t.push(p)
            }
            if (t.length == 3) break
        }
        return t
    }
    static 创建boss(id: string) {
        let { x, y } = ArrayUtil.randomElement(刷怪点)
        // 蛛网女皇
        if (id == 'nnwq') {
            // nnws
            let u = GameMonsters.create('nnws', x, y)
            IssuePointOrderById(u, OrderId.Attack, 0, 0)
        }
        let u = GameMonsters.create(id, x, y)
        if (id == 'nkol') {
            GameMonsters.狗头人boss(u)
        }
        IssuePointOrderById(u, OrderId.Attack, 0, 0)
    }
    static 狗头人boss(u: unit) {}
}
